package com.briup.authentication.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthenticationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许表单提交，在检查accessToken有效的情况下
        security.allowFormAuthenticationForClients().checkTokenAccess("permitAll()");
    }

    /**
     * 配置客户端信息，分配client_id client_secret
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("briup_oauth") // 设置client_id
                .secret(passwordEncoder.encode("briup_secret")) // 设置client_secret
                .authorizedGrantTypes("authorization_code") // 设置授权类型为授权码类型
                .scopes("all") // 设置访问接口范围，这里设置为所有
                .resourceIds("briup_resource") // 设置资源id
                .redirectUris("http://localhost:9999/callback"); // 回调地址，会把授权码返回给该地址
    }

}
